<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="800" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm">
      <template #selectAddress="{ model, field }">
        <a-input v-model:value="model[field]" readonly placeholder="请设置门店地址" @click="handleOpenSelectMapAddress(model[field])" />
      </template>

      <template #tags="{ model, field, schema }">
        <a-row :gutter="8">
          <a-col :sm="20" :md="20" :lg="20" :xl="20">
            <ApiSelect v-bind="schema.componentProps" :alwaysLoad="true" :value="model[field]" ref="tagSelectRef" />
          </a-col>
          <a-col :sm="4" :md="4" :lg="4" :xl="4">
            <a-button block style="width: 100%" @click="handleOpenTag()" type="primary">管理</a-button>
          </a-col>
        </a-row>
      </template>
    </BasicForm>
  </BasicDrawer>

  <SelectMapAddress @register="registerSelectMapAddressModal" @success="handleSelectAddressSuccess" />
  <TagList @register="registerTagList" />
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { useModal } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { ApiSelect } from "/@/components/Form/index"
  import { formSchema } from "./store.data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdateStore } from "/@/api/misc/store"
  import SelectMapAddress from "/@/components/Form/src/my/components/SelectMapAddress/index.vue"
  import TagList from '../tag/ListModel.vue'
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const rowId = ref("")
  const selectAddress = ref<any>({})
  const tagSelectRef = ref()

  const [registerSelectMapAddressModal, { openModal: openSelectMapAddressModal }] = useModal()
  const [registerTagList, { openModal: openTagList }] = useModal()
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    // labelWidth: 90,
    schemas: formSchema,
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
    showActionButtonGroup: false,
  })

  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    setDrawerProps({ confirmLoading: false, showFooter: true, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate
      if (unref(isUpdate)) {
        rowId.value = data.record.id
      } else {
        // 设置默认值
        data.record = {}
        data.record.openTime = [
          {
            openWeek: ["1", "2", "3", "4", "5", "6", "7"],
            startTime: "06:00",
            endTime: "22:00",
          },
        ]
      }
      selectAddress.value.addressDetail = data.record.addressDetail

      if (typeof data.record === "object") {
        setFieldsValue({
          ...data.record,
          openTime: JSON.stringify(data.record.openTime),
          tags: data.record.tags?.split(","),
        })
      }
      tagSelectRef.value.handleFetch()
    } finally {
      setDrawerProps({ loading: false })
    }
  })
  //获取标题
  const getTitle = computed(() => (isUpdate.value ? "编辑门店" : "创建门店"))

  const handleOpenSelectMapAddress = (address) => {
    selectAddress.value.address = address
    openSelectMapAddressModal(true, { selectAddress: selectAddress.value })
  }

  const handleOpenTag = () => {
    openTagList(true, {})
  }

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate()
      console.log("values", values)

      setDrawerProps({ confirmLoading: true })
      await saveOrUpdateStore(
        {
          ...values,
          openTime: JSON.parse(values.openTime),
          addressDetail: unref(selectAddress).addressDetail,
        },
        isUpdate.value
      )
      closeDrawer()
      emit("success", { values: { ...values, id: rowId.value } })
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const handleSelectAddressSuccess = (useAddress) => {
    console.log(`selectAddress is`, useAddress)
    selectAddress.value = useAddress
    setFieldsValue({ ...useAddress })
  }
</script>
